<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>利用观察者模式实现布局通信</title>
  </head>
  <style>
    .layout {
      display: flex;
      flex-direction: column;
      height: 800px;
    }
    .layout .header {
      height: 80px;
      background-color: pink;
    }
    .layout .container {
      display: flex;
      flex-direction: row;
      flex: 1;
    }
    .layout .sidebar {
      width: 200px;
      height: 100%;
      background-color: skyblue;
    }
    .layout .content {
      flex: 1;
      background-color: blueviolet;
    }
    .sidebar ul {
      padding: 0;
    }
    .sidebar li {
      margin-bottom: 2px;
      list-style: none;
      height: 30px;
      border: 1px solid;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
    }
  </style>
  <body>
    <div class="layout">
      <header class="header"></header>
      <div class="container">
        <div class="sidebar">
          <ul>
            <li>商品</li>
            <li>人员</li>
            <li>物资</li>
          </ul>
        </div>
        <div class="content"></div>
      </div>
    </div>
  </body>
  <script>
    class Subject {
      constructor() {
        this.observers = [];
      }

      add(observer) {
        this.observers.push(observer);
      }

      remove(observer) {
        this.observers = this.observers.filter(
          (obs) => obs.name === observer.name
        );
      }
    }

    class Observer {
      constructor(selector) {
        this.element = document.querySelector(selector);
      }

      notify(data) {
        this.element.innerHTML = data;
      }
    }

    const subject = new Subject();
    console.log(subject);
    const content_observer = new Observer(".content");
    const header_observer = new Observer(".header");

    subject.add(content_observer);
    subject.add(header_observer);

    (function () {
      const sideBarList = document.querySelectorAll(".sidebar li");
      console.log(sideBarList);
      sideBarList.forEach((li) => {
        li.addEventListener("click", function () {
            subject.observers.forEach(observer => {
                observer.notify(li.innerHTML)
            })
        }, false);
      });
    })();
  </script>
</html>
